<template>
  <codemirror
    class="json-code-mirror"
    ref="myCm"
    v-model="codeStr"
    :options="cmOptions"
    @input="onCmCodeChange"
    @ready="onCmReady"
  ></codemirror>
</template>

<script>
import { codemirror } from "vue-codemirror";
import "codemirror/mode/javascript/javascript.js";

import "codemirror/lib/codemirror.css";

import "codemirror/mode/css/css";

import "codemirror/theme/base16-light.css";
import "codemirror/addon/selection/active-line";

import FormatMixin from "./FormatMixin";
export default {
  name: "JsonCodeMirror",
  mixins: [FormatMixin],
  components: {
    codemirror
  },
  props: {
    code: {
      type: String,
      default: ""
    },
    readOnly: {
      type: Boolean,
      default: false
    },
    lineNumbers: {
      type: Boolean,
      default: true
    }
  },
  model: {
    prop: "code",
    event: "change"
  },
  data() {
    return {
      codeStr: "",
      cmOptions: {
        // codemirror options
        tabSize: 2,
        mode: "application/json",
        readOnly: this.readOnly,
        smartIndent: true,
        theme: "base16-light",
        lineNumbers: this.lineNumbers,
        line: true,
        indentWithTabs: true,
        lineWrapping: true,
        foldGutter: false,
        gutters: ["CodeMirror-linenumbers", "CodeMirror-lint-markers"],
        showCursorWhenSelecting: true,
        spellcheck: false
      }
    };
  },
  watch: {
    code: {
      immediate: true,
      handler(val) {
        this.codeStr = val;
      }
    }
  },
  methods: {
    onCmCodeChange(newCode) {
      this.$emit("change", newCode);
    },
    onCmReady(cm) {
      this.editor = cm;
    }
  }
};
</script>
<style lang="less">
.json-code-mirror {
  line-height: 24px;
}
.vue-codemirror {
  .CodeMirror {
    font-family: SFMono-Regular, Consolas, "Liberation Mono", Menlo, Courier,
      monospace;
    background-color: #fff;
    border: 1px solid #d2dae8;
    border-radius: 4px;

    span {
      &.cm-string {
        &.cm-property {
          color: #005cc5;
        }
      }
      &.cm-number {
        color: #005cc5;
      }
      &.cm-atom {
        color: #905;
      }
      &.cm-string {
        color: #690;
      }
      &.cm-tag {
        color: #22863a;
      }
      &.cm-attribute {
        color: #6f42c1;
      }
      &.cm-comment {
        color: #6a737d;
      }
    }

    .CodeMirror-gutters {
      background-color: #fff;
    }

    &.CodeMirror-wrap pre.CodeMirror-line,
    &.CodeMirror-wrap pre.CodeMirror-line-like {
      word-wrap: break-word;
      white-space: pre-wrap;
      word-break: break-word;
    }
  }
}
</style>
